package com.linkhub.oms.component.mp.wrapper;

import com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * @Description: WrapperConverter
 * @Author: echo
 * @Date: 2021/11/9 16:32
 * @Version: 1.0
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class WrapperConverter {

    /**
     * 转换UpdateWrapper更新条件到QueryWrapper
     *
     * @param updateWrapper updateWrapper
     * @param <T>           T
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> convertUpdateCondition(AbstractWrapper<?, ?, ?> updateWrapper) {
        return convertCondition(updateWrapper);
    }

    /**
     * 转换lambdaWrapper更新条件到QueryWrapper
     *
     * @param lambdaWrapper lambdaWrapper
     * @param <T>           T
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> convertLambdaCondition(AbstractLambdaWrapper<T, ?> lambdaWrapper) {
        return convertCondition(lambdaWrapper);
    }

    /**
     * 转换lambdaWrapper到QueryWrapper
     *
     * @param lambdaWrapper lambdaWrapper
     * @param <T>           T
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> convertLambdaWrapper(AbstractLambdaWrapper<T, ?> lambdaWrapper) {
        QueryWrapper<T> result = convertCondition(lambdaWrapper);
        result.select(lambdaWrapper.getSqlSelect());
        return result;
    }

    private static <T> QueryWrapper<T> convertCondition(AbstractWrapper<?, ?, ?> originWrapper) {
        QueryWrapperAdapter<T> wrapperAdapter = new QueryWrapperAdapter<>(originWrapper.getParamNameValuePairs());
        wrapperAdapter.addCondition(originWrapper.getExpression());
        return wrapperAdapter;
    }
}
